package com.leetcode.LeetCode精选TOP面试题;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author 覃国强
 * @date 2022-07-08 15:35
 */
public class 题库_0215_数组中的第K个最大元素 {

  static
  class Solution {
    public int findKthLargest(int[] nums, int k) {
      PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, Comparator.reverseOrder());
      for (int i = 0; i < nums.length && i < k; ++i) {
        priorityQueue.add(nums[i]);
      }

      for (int i = k; i < nums.length; ++i) {
        if (nums[i] > priorityQueue.peek()) {
          priorityQueue.poll();
          priorityQueue.add(nums[i]);
        }
      }

      return priorityQueue.peek();
    }
  }

}
